package com.kuangjia.student_ems.repository;

import com.kuangjia.student_ems.entity.Notification;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface NotificationRepository extends JpaRepository<Notification, Long> {
    Page<Notification> findByUserIdAndIsRead(Long userId, Boolean isRead, Pageable pageable);
    Page<Notification> findByUserId(Long userId, Pageable pageable);
    Long countByUserIdAndIsRead(Long userId, Boolean isRead);
    
    // 搜索方法
    Page<Notification> findByUserIdAndTitleContainingOrContentContaining(Long userId, String titleKeyword, String contentKeyword, Pageable pageable);
    Page<Notification> findByUserIdAndIsReadAndTitleContainingOrContentContaining(Long userId, Boolean isRead, String titleKeyword, String contentKeyword, Pageable pageable);
    
    // 查询用户消息和系统消息（user_id为null的消息）
    @Query("SELECT n FROM Notification n WHERE (n.userId = :userId OR n.userId IS NULL)")
    Page<Notification> findByUserIdOrSystemMessage(@Param("userId") Long userId, Pageable pageable);
    
    @Query("SELECT n FROM Notification n WHERE (n.userId = :userId OR n.userId IS NULL) AND n.isRead = :isRead")
    Page<Notification> findByUserIdOrSystemMessageAndIsRead(@Param("userId") Long userId, @Param("isRead") Boolean isRead, Pageable pageable);
    
    @Query("SELECT n FROM Notification n WHERE (n.userId = :userId OR n.userId IS NULL) AND (n.title LIKE %:keyword% OR n.content LIKE %:keyword%)")
    Page<Notification> findByUserIdOrSystemMessageAndKeyword(@Param("userId") Long userId, @Param("keyword") String keyword, Pageable pageable);
    
    @Query("SELECT n FROM Notification n WHERE (n.userId = :userId OR n.userId IS NULL) AND n.isRead = :isRead AND (n.title LIKE %:keyword% OR n.content LIKE %:keyword%)")
    Page<Notification> findByUserIdOrSystemMessageAndIsReadAndKeyword(@Param("userId") Long userId, @Param("isRead") Boolean isRead, @Param("keyword") String keyword, Pageable pageable);
    
    // 统计未读消息数量（包括系统消息）
    @Query("SELECT COUNT(n) FROM Notification n WHERE (n.userId = :userId OR n.userId IS NULL) AND n.isRead = :isRead")
    Long countByUserIdOrSystemMessageAndIsRead(@Param("userId") Long userId, @Param("isRead") Boolean isRead);
} 